package net.lovesrc.allin.jobs.backup;

import com.alibaba.fastjson.JSONObject;
import net.lovesrc.allin.biz.gt.GtPreOrder;
import net.lovesrc.allin.biz.gt.GtService;
import net.lovesrc.allin.biz.user.UserService;
import net.lovesrc.allin.jobs.base.BaseJob;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

//@Component
@Profile("live")
public class GtAutoNewJyJob extends BaseJob {

    @Autowired
    private GtService gtService;

    @Override
    public void runOnce() {
        if (gtService.isNotJyTime()) {
            return;
        }
        Integer ingQty = jdbcTemplate.queryForObject("select count(1) from t_gt_jy where status in ('New', 'Waiting_Buyer_Pay', 'Waiting_Seller_Confirm')", int.class);
        if (ingQty >= 4) {
            return;
        }
        boolean newNextJy = newNextJy();
        if (newNextJy) {
            if (mustJyToMyAccount()) {
                doSellTenToMyAccount();
            } else {
                gtService.newSysJy(UserService.SYSTEM);
            }
        }
    }

    private boolean newNextJy() {
        // 大于一定的时长，自动交易一笔
        Date maxJyTime = jdbcTemplate.queryForObject("select max(insertTime) from t_gt_jy", Date.class);
        Integer newJyIntervalMinutes = tryGetProperties(int.class, 30, "Gt_Auto_New_Jy_Interval_Minutes");
        if (System.currentTimeMillis() - maxJyTime.getTime() >= newJyIntervalMinutes * DateUtils.MILLIS_PER_MINUTE) {
            return true;
        }
        String mobile = jdbcTemplate.queryForObject("select mobile from v_gt_account order by updateTime desc limit 1", String.class);
        List<GtPreOrder> preBuyOrders = gtService.getPreBuyOrders(mobile);
        if (preBuyOrders != null && preBuyOrders.size() > 0) {
            int maxJyId = preBuyOrders.stream()
                    .mapToInt(r -> r.getId())
                    .max()
                    .getAsInt();
            Integer newJyInterval = tryGetProperties(int.class, 80, "Gt_Auto_New_Jy_Interval");
            int latestJyId = jdbcTemplate.queryForObject("select max(jyId) from t_gt_jy", int.class);
            return maxJyId >= latestJyId + newJyInterval;
        }
        return false;
    }

    /**
     * 前N笔，无转入大号
     */
    private boolean mustJyToMyAccount() {
        if (jdbcTemplate.queryForObject("select count(1) from v_gt_other_account where ye >= 10", int.class) <= 13) {
            return false;
        }
        Integer jyToMyAccountInterval = tryGetProperties(int.class, 2, "Gt_Auto_New_Jy_To_My_Interval");
        return jdbcTemplate.queryForObject("select count(1) from (" +
                " select * from t_gt_jy order by jyId desc limit ?" +
                " ) r" +
                " where" +
                " r.buyerMobile in (select mobile from v_gt_my_account)", int.class, jyToMyAccountInterval) == 0;
    }

    private void doSellTenToMyAccount() {
        int dayOfYear = Calendar.getInstance().get(Calendar.DAY_OF_YEAR);
        String myAccountOrder = dayOfYear % 2 == 0 ? "desc" : "asc";
        List<String> latestBuyerMobiles = jdbcTemplate.queryForList("select buyerMobile from t_gt_jy where buyerMobile in (select mobile from v_gt_my_account) order by insertTime desc limit 5", String.class);
        JSONObject matchedRow = queryForRow(jdbcTemplate, "select a.mobile, count(jy.jyId) jyQty, a.realName, a.sort " +
                " from t_gt_account a " +
                " left join (select * from t_gt_jy where insertTime > date(now() - interval 3 day)) jy " +
                " on a.mobile = jy.buyerMobile " +
                " where a.isMyAccount = 1 " +
                " and a.mobile not in (select mobile from v_gt_jy_ing_mobile) " +
                " and a.mobile not in (" + StringUtils.repeat("?", ",", latestBuyerMobiles.size()) + ")" +
                " group by a.mobile " +
                " order by count(jy.jyId) asc, a.sort " + myAccountOrder +
                " limit 1", latestBuyerMobiles.toArray(new Object[latestBuyerMobiles.size()]));
        String buyerMobile = matchedRow.getString("mobile");
        JSONObject buyer = queryForRow(jdbcTemplate, "select * from v_gt_my_account where mobile = ?", buyerMobile);
        if (buyer == null) {
            return;
        }
        String buyerRoot = buyer.getString("root");
        JSONObject seller = queryForRow(jdbcTemplate, "select * from v_gt_other_account" +
                " where mobile not in (select mobile from v_gt_can_not_sell_now)" +
                " and mobile not in (select mobile from v_gt_jy_ing_mobile)" +
                " and mobile not in (select buyerMobile from t_gt_jy where sellerMobile = ? and buyerMobile is not null)" +
                " and mobile not in (select sellerMobile from t_gt_jy where buyerMobile = ? and sellerMobile is not null)" +
                " and ye6 >= 10" +
                " and ye1 >= 13" +
                " and root <> ?" +
                " and updateTime < now() - interval 20 minute" +
                " order by rand() desc limit 1", buyerMobile, buyerMobile, buyerRoot);
        if (seller == null) {
            return;
        }
        String sellerMobile = seller.getString("mobile");
        gtService.newJy(UserService.SYSTEM, "SellTen2MyAccount", buyerMobile, sellerMobile);
    }

    @Override
    protected long intervalMilliseconds() {
        return TimeUnit.SECONDS.toMillis(30);
    }

}
